package zack.project.trigger.listener;

import zack.project.domain.award.event.SendAwardMessageEvent;
import zack.project.domain.award.model.entity.DistributeAwardEntity;
import zack.project.domain.award.service.IAwardService;
import zack.project.types.event.BaseEvent;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author A1793
 * 接收消息
 */
@Slf4j
@Component
public class SendAwardCustomer {

    @Value("${spring.rabbitmq.topic.send_award}")
    private String topic;

    @Resource
    private IAwardService awardService;

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.send_award}"))
    public void listen(String message) {
        try {
            log.info("监听用户奖品发送消息 topic: {} message: {}", topic, message);
            BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> eventMessage =
                    JSON.parseObject(message,
                            new TypeReference<BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage>>() {
            }.getType());

            SendAwardMessageEvent.SendAwardMessage data = eventMessage.getData();

            //构建发奖实体
            DistributeAwardEntity distributeAwardEntity = new DistributeAwardEntity();
            distributeAwardEntity.setAwardConfig(data.getAwardConfig());
            distributeAwardEntity.setAwardId(data.getAwardId());
            distributeAwardEntity.setUserId(data.getUserId());
            distributeAwardEntity.setOrderId(data.getOrderId());

            awardService.distributeAward(distributeAwardEntity);


        } catch (Exception e) {

            log.error("监听用户奖品发送消息，消费失败 topic: {} message: {}", topic, message);

       //    throw e;

        }

    }

}
